﻿using System;
using gms.data;
using gms.security;
using gms.system;

namespace gms.page.admin {
	public partial class playermgr_add : GMSPage {
		public bool posted = false;

		public playermgr_add() : base() {
			this.Load += new EventHandler(playermgr_add_Load);
		}

		void playermgr_add_Load(object sender, EventArgs e) {
			Authorization.AuthorizeOrForward(AclType.ManagePlayers);

			if (Request.Form.Count != 0) {
				posted = true;
			}

			Player new_player = new Player();
			string password = "";

			if (posted) {
				if (Request.Form["player_first_name"] != null) {
					if (Request.Form["player_first_name"].Length != 0) {
						new_player.first_name = Request.Form["player_first_name"];
					}
					else {
						posted = false;
						throw new Exception("First Name must not be empty");
					}
				}
				else {
					posted = false;
					throw new Exception("First Name must not be empty");
				}

				if (Request.Form["player_last_name"] != null) {
					if (Request.Form["player_last_name"].Length != 0) {
						new_player.last_name = Request.Form["player_last_name"];
					}
				}

				if (Request.Form["player_email"] != null) {
					if (Request.Form["player_email"].Length != 0) {
						new_player.email = Request.Form["player_email"];
					}
					else {
						posted = false;
						throw new Exception("Email must not be empty");
					}
				}
				else {
					posted = false;
					throw new Exception("Email must not be empty");
				}

				if (Request.Form["player_password"] != null) {
					if (Request.Form["player_password"].Length != 0) {
						password = Request.Form["player_password"];
					}
					else {
						posted = false;
						throw new Exception("Password must not be empty");
					}
				}
				else {
					posted = false;
					throw new Exception("Password must not be empty");
				}

				new_player.address = "";
			}

			if (posted) {
				if (Player.email_exists(new_player.email)) {
					posted = false;
					throw new Exception("Email is already in use");
				}
			}

			if (posted) {
				new_player.salt = Hashing.GenerateRandomByteArray();
				new_player.update_password(password);

				nhdb.session.BeginTransaction();
				nhdb.session.Save(new_player);
				nhdb.session.Transaction.Commit();

				Response.Redirect("playermgr.aspx");
			}
		}
	}
}